﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
using System.Net;


using NewPanda.Configure;
using NewPanda.ViewModel;
using MusicPlayerLib.ViewModel;
using MusicPlayerLib.DataModel;
using MusicPlayerLib.Utils;

using P2PLib.Client.DataModel;
using P2PLib.Client.ViewModel;
using P2PLib.Client.Utils;
using P2PLib.Common.DataModel;

namespace NewPanda
{
    /// <summary>
    /// 该类包含了程序所用的一个工具方法;
    /// </summary>
    public class AppUtils
    {
        /// <summary>
        /// 创建程序中所用的几个文件夹;
        /// </summary>
        public static void CreateFolders()
        {
            string[] names ={
                               RedPandaConfig.ArtistFolderNmae,
                               RedPandaConfig.CoverFolderName,
                               RedPandaConfig.LyricFolderName,
                               RedPandaConfig.PlaylistFolderName,
                               RedPandaConfig.DownloadFolderName};

            string baseDir=Environment.CurrentDirectory;
            foreach(string s in names)
            {
                string path = baseDir + "\\" + s;
                if(!(Directory.Exists(path)))
                    Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 该方法加载音乐模块相关的信息;
        /// </summary>
        /// <returns></returns>
        public static MusicViewModel LoadMusicViewModel()
        {
            MusicViewModel mvm = new MusicViewModel();
            mvm.ListOfPlaylist = LoadPlaylists();
            mvm.MediaLibrary = LoadMediaLibrary();

            //设置初始化时的播放列表以及曲目;
            if (mvm.ListOfPlaylist.Count > 0)
            {
                mvm.CurrentPlaylist = mvm.ListOfPlaylist[0];
                if (mvm.CurrentPlaylist.Tracks.Count > 0)
                    mvm.CurrentTrack = new AudioFileViewModel(mvm.CurrentPlaylist.Tracks[0]);
            }
            return mvm;
        }

        /// <summary>
        /// 从文件夹中加载播放列表
        /// </summary>
        /// <returns></returns>
        public static ObservableCollection<PlaylistViewModel> LoadPlaylists()
        {
            string path = App.dir + "\\" + RedPandaConfig.PlaylistFolderName;

            ObservableCollection<PlaylistViewModel> playlists =
                            new ObservableCollection<PlaylistViewModel>();
            try
            {
                FileInfo[] files = new DirectoryInfo(path).GetFiles();
                foreach (FileInfo f in files)
                {
                    Playlist pl = PlaylistUtils.LoadSingleList(f.FullName);
                    if (pl != null)
                    {
                        PlaylistViewModel pvm = new PlaylistViewModel(pl);
                        playlists.Add(pvm);
                    }
                }
            }
            catch (Exception e)
            {
                //e.StackTrace;
            }
            return playlists;
        }


        /// <summary>
        /// 加载媒体库信息；
        /// </summary>
        /// <returns></returns>
        public static MediaLibraryViewModel LoadMediaLibrary()
        {
            string path = App.dir + "\\library.xml";
            FileInfo file = new FileInfo(path);
            if(!file.Exists)
            {
                MusicPlayerUtils.SaveMediaLibary(path, new MediaLibrary());
            }

            MediaLibrary ml = MusicPlayerUtils.LoadMediaLibrary(App.dir + "\\library.xml");

            ObservableCollection<AlbumViewModel> albums=
                new ObservableCollection<AlbumViewModel>();
            ObservableCollection<ArtistViewModel> artists=
                new ObservableCollection<ArtistViewModel>();
            ObservableCollection<AudioFile> tracks = new ObservableCollection<AudioFile>();
            
            //添加所有Tracks
            foreach (AudioFile af in ml.Tracks)
            {
                tracks.Add(af);
            }

            //获得所有的Albums
            foreach(Album album in ml.Albums)
            {
                ObservableCollection<AudioFile> afs=new ObservableCollection<AudioFile>();

                var albumTracks=from t in tracks
                                where t.Album.Equals(album.Title)&&t.Artist.Equals(t.Artist)
                                select t;
                foreach(AudioFile t in albumTracks)
                {
                    afs.Add(t);
                }
                albums.Add(new AlbumViewModel(album,afs));
            }

            //获得所有的Artists

            foreach(Artist artist in ml.Artists)
            {
                ObservableCollection<AlbumViewModel> albumCollection=
                    new ObservableCollection<AlbumViewModel>();

                var artistAlbums=from a in albums
                                 where a.Info.Artist.Equals(artist.Name)
                                 select a;
                foreach(AlbumViewModel album in artistAlbums)
                {
                    albumCollection.Add(album);
                }

                artists.Add(new ArtistViewModel(artist,albumCollection));
            }

            return new MediaLibraryViewModel(artists, albums, tracks);

        }


        public static FileShareViewModel LoadFileShareViewModel()
        {
            DownloadTaskList taskList = LoadDownloadTasks();

            SharedFileLibrary fileLibrary= LoadFileLibrary();

            FileShareViewModel fsvm = new FileShareViewModel(taskList, fileLibrary);
            return fsvm;
        }

        /// <summary>
        /// 加载下载任务列表;
        /// </summary>
        /// <returns></returns>
        public static DownloadTaskList  LoadDownloadTasks()
        {
            string path=App.dir+"\\download_tasks.xml";
            //判断path所指定的文件是否存在;
            FileInfo file = new FileInfo(path);
            if (!file.Exists)
            {
                //不存在则创建一个新的空的列表;
                DownloadTaskUtils.SaveDownloadTasks(new DownloadTaskList(), path);
            }

            DownloadTaskList list = DownloadTaskUtils.LoadDownloadTasks(path);

            return list;
        }

        /// <summary>
        /// 加载用户的共享文件
        /// </summary>
        /// <returns></returns>
        public static SharedFileLibrary LoadFileLibrary()
        {
            string path = App.dir + "\\sharedFiles.xml";
            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                List<string> dirs = new List<string>();
                dirs.Add(App.dir + "\\" + RedPandaConfig.DownloadFolderName);
                SharedFileLibraryUtils.SaveFileList(path, new SharedFileLibrary(dirs));
            }

            SharedFileLibrary fileLibrary = SharedFileLibraryUtils.LoadSharedFileLibrary(path);
            return fileLibrary;
        }

        /// <summary>
        /// get the client info 
        /// </summary>
        /// <returns></returns>
        public static ClientInfo GetClientInfo()
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
            string strAddr = ipEntry.AddressList[0].ToString(); //假设本地主机为单网卡 
            int port = RedPandaConfig.port;

            ClientInfo info = new ClientInfo(strAddr, port);
            return info;
        }

    }
}
